import { defineStore } from "pinia"
import { ref } from 'vue'
import { useWatermark } from '@/hooks/web/useWatermark'

const { setWatermark, clear } = useWatermark()

export const loginKey = 'seed-dev-user'
export interface User {
  id: string,
  name?: string,
  avatar?: string,
  username: string
}

export default defineStore('userStore', () => {
  const user = ref<User>()
  
  async function login(loginUser: User) {
    user.value = loginUser
    localStorage?.setItem(loginKey, JSON.stringify(loginUser))

    setWatermark(loginUser.name || loginUser.username)
  }

  function logout() {
    user.value = undefined

    localStorage?.removeItem(loginKey)
    clear()
  }

  function getLoginInfo() {
    if(user.value) return user.value

    const item = localStorage?.getItem(loginKey)
    if(item) {
      user.value = JSON.parse(item)
      setWatermark(user.value.name || user.value.username)
    }

    return user.value
  }

  function isLogin() {
    return !!getLoginInfo()
  }

  return { login, logout, isLogin, getLoginInfo }
})
